'use strict'

let globalObject = require('../server/globalobject')
let child_process = require('child_process')
let RootServer = require('../distributed/rootserver')
let Child = require('../distributed/child')

//master服务器类
class Master {
	constructor(configpath, mainpath) {
		this.configpath = configpath
		this.mainpath = mainpath
		Master.globalObject = globalObject
		this.config = require(this.configpath)
		globalObject.config = this.config
		this.rootServer = new RootServer('master')
		this.rootServer.master = true
		globalObject.rootServer = this.rootServer
	}

	start() {
		let self = this
		let mastercnf = this.config['master']
		let rootport = mastercnf['rootport']
		this.rootServer.createServer(rootport)

		let sersconf = this.config['servers']
			/**/
		for (let sername in sersconf) {
			let command = 'iojs'
			let args = ['--es_staging', this.mainpath, sername, this.configpath]
				//command = 'iojs --es_staging ' + this.mainpath + ' ' + sername + ' ' + this.configpath
			var child = child_process.spawn(command, args);
			child.stdout.on('data', function(data) {
				var msg = data.toString()
				process.stdout.write(msg)
			});

			child.stderr.on('data', function(chunk) {
				var msg = chunk.toString()
				process.stderr.write(msg)
			})
		}

	}

}

module.exports = Master
